package com.shuoyue.ycgk.ui.account;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.shuoyue.ycgk.Constant;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.appcatch.MemeryCatch;
import com.shuoyue.ycgk.appcatch.SPUtils;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.entity.UserInfo;
import com.shuoyue.ycgk.ui.common.CstWebActivity;
import com.shuoyue.ycgk.ui.main.MainTabActivity;
import com.shuoyue.ycgk.utils.DevicesUtil;
import com.shuoyue.ycgk.utils.SimpleCodeUtil;


import org.greenrobot.eventbus.EventBus;

import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

public class BindPhoneActivity extends BaseMvpActivity<BindPhoneContract.Presenter>
        implements BindPhoneContract.View {

    public final static int REQUEST_CODE = 4326;
    @BindView(R.id.phone_num)
    EditText phoneNum;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.getCode)
    TextView getCode;
    private TimeCount time;
    String openId;
    String accessToken;

    public static void start(Activity context, String openId, String accessToken) {
        context.startActivityForResult(new Intent(context, BindPhoneActivity.class)
                        .putExtra("srequestCode", REQUEST_CODE)
                        .putExtra("openId", openId)
                        .putExtra("accessToken", accessToken)
                ,
                REQUEST_CODE);

    }

    /**
     * 初始化layouy
     */
    @Override
    protected int getLayoutId() {
        return R.layout.activity_bind_phone;
    }

    /**
     * 初始化布局
     */
    @Override
    protected void initView() {
        UserInfo userInfo = SPUtils.getUserInfo(mContext);
        if (userInfo != null) {
            MemeryCatch.token = userInfo.getToken();
            startActivity(new Intent(mContext, MainTabActivity.class));
            finish();
        }
        time = new TimeCount(60000, 1000);
    }

    @Override
    public void initData() {
        openId = getIntent().getStringExtra("openId");
        accessToken = getIntent().getStringExtra("accessToken");
        super.initData();
        mPresenter = new BindPhoneContract.Presenter();
        mPresenter.attachView(this);
    }

    @OnClick({R.id.back, R.id.getCode, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.getCode:
                String phone = phoneNum.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    toast("请输入手机号码");
                    return;
                }
                mPresenter.sendSms(phone);
                break;
            case R.id.submit:
                login();
                break;
        }
    }

    void login() {
        String phone = phoneNum.getText().toString();
        String sms = editCode.getText().toString();
        if (sms.length() == 0) {
            toast("请输入验证码");
            return;
        }
        String deviceName = null, imei = null;
        if (EasyPermissions.hasPermissions(mContext, Manifest.permission.READ_PHONE_STATE)) {
            deviceName = DevicesUtil.getManuFacturer() + DevicesUtil.getModel();
//            imei = DevicesUtil.getIMEI(mContext);
            imei = SimpleCodeUtil.getSimpleDeviceCode(mContext);
            if (TextUtils.isEmpty(imei)) {
                UUID uuid = UUID.randomUUID();
                imei = uuid.toString();
                SimpleCodeUtil.writeSimpleDeviceCode(mContext,imei);
            }
        } else {
            EasyPermissions.requestPermissions(this, "设备信息权限",
                    109, Manifest.permission.READ_PHONE_STATE);
            toast("请打开获取手机信息权限");
            return;
        }

        mPresenter.bindPhone(openId, accessToken, phone, sms, imei, deviceName);
    }

    /**
     * 发送验证码后
     */
    @Override
    public void sendSuc(String phone) {
        toast("验证码发送成功");
        time.start();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        if (time != null) {
            time.cancel();
        }
    }

    @Override
    public void bindSuc(UserInfo userInfo) {
        if (userInfo != null) {
            MemeryCatch.token = userInfo.getToken();
            SPUtils.updateUserInfo(mContext, userInfo);
            setResult(RESULT_OK);
            finish();
        }
    }


    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
//            getCode.setBackgroundResource(R.drawable.bg_login_send_code_a);
            getCode.setTextColor(ContextCompat.getColor(mContext, R.color.themeColor));
            getCode.setEnabled(false);
            getCode.setText(millisUntilFinished / 1000 + "s");
        }

        @Override
        public void onFinish() {
//            getCode.setBackgroundResource(R.drawable.bg_login_send_code);
            getCode.setTextColor(ContextCompat.getColor(mContext, R.color.all_orange_color));
            getCode.setEnabled(true);
            getCode.setText("重新获取");
        }
    }
}
